package com.agnes.network.callback;

import android.app.Activity;
import android.content.Context;

import com.agnes.network.Const;
import com.agnes.network.dialog.ProgressDialog;

import java.util.List;

/**
 * Desc:
 * Creator ling
 * Date:   2017/9/28 0028 15:50
 */

public abstract class RespCallbackImpl<D> implements RespCallback<D> {
    private final String TAG = this.getClass().getName();

    protected Context mContext;
    private ProgressDialog progressDialog;
    private long startReqTime;

    private boolean showLoading;

    public RespCallbackImpl(Context context) {
        this.mContext = context;
        progressDialog = new ProgressDialog(context);
    }

    public RespCallbackImpl(Context context, boolean showLoading) {
        this.mContext = context;
        progressDialog = new ProgressDialog(context);
        this.showLoading = showLoading;
    }

    @Override
    public void onSuccess(String message, D data) {
        finish();
    }

    @Override
    public void onSuccess(String message, List<D> datas) {
        finish();
    }

    @Override
    public void onFailure(Throwable e) {
        finish();
    }

    @Override
    public void onError(String code, String failureMsg, D data) {
        finish();

        // 会话过期，跳转到登录页
        if (Const.USER_NOT_EXIST_CODE.equals(code)) {
            onNotLogin();
        }

        toastErrorMsg(code, failureMsg, data);
    }

    @Override
    public void onError(String code, String failureMsg, List<D> dataList) {
        finish();

        // 会话过期，跳转到登录页
        if (Const.USER_NOT_EXIST_CODE.equals(code)) {
            onNotLogin();
        }

        toastErrorMsg(code, failureMsg, dataList);
    }

    // 处理错误信息调用
    protected abstract void toastErrorMsg(String code, String failureMsg, D data);

    // 处理错误信息调用
    protected abstract void toastErrorMsg(String code, String failureMsg, List<D> dataList);

    protected abstract void onNotLogin();

    @Override
    public void onStart() {
        start();
    }

    @Override
    public void onFinish() {
        finish();
    }

    private void start() {
        startReqTime = System.currentTimeMillis();
        if (progressDialog != null && showLoading && !progressDialog.isShowing() && mContext != null && !((Activity) mContext).isFinishing()) {
            progressDialog.show();
        }
    }

    private void finish() {
        if (progressDialog != null && progressDialog.isShowing() && mContext != null && !((Activity) mContext).isFinishing())
            progressDialog.dismiss();
    }
}
